package com.my.commonlib.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.my.commonlib.BaseApplication;

import java.io.File;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import okhttp3.Cookie;


public class BaseTools {

    /**
     * scrollview和listview共存的解决方法
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    public static String mathTime_s(String time, String format) {
        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if (TextUtils.isEmpty(time)) {
                return "";
            }
            Date date = dfs.parse(time);
            dfs = new SimpleDateFormat(format);
            dfs.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
            return dfs.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName() {
        String versionName = "";
        try {
            PackageManager pm = BaseApplication.getApp().getPackageManager();
            PackageInfo pi = pm.getPackageInfo(BaseApplication.getApp().getPackageName(), 0);
            versionName = pi.versionName;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }

    /**
     * 返回当前程序版本号
     */
    public static int getAppVersionCode() {
        int versionCode = 1;
        try {
            PackageManager pm = BaseApplication.getApp().getPackageManager();
            PackageInfo pi = pm.getPackageInfo(BaseApplication.getApp().getPackageName(), 0);
            versionCode = pi.versionCode;

        } catch (Exception e) {
            versionCode = 1;
        }
        Logger.i("=====getAppVersionCode=" + versionCode);
        return versionCode;
    }


    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        int statusBarHeight = 0;
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object o = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = (Integer) field.get(o);
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
            if (context instanceof Activity) {
                Rect frame = new Rect();
                ((Activity) context).getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
                statusBarHeight = frame.top;
            }
        }
        return statusBarHeight;
    }


    public static void setTitleMargrStaust(View mView) {
        if (SDKUtil.hasKitKat()) {
            if (mView.getLayoutParams() instanceof LinearLayout.LayoutParams) {
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mView.getLayoutParams();
                int staust = BasePersonSharePreference.getStatusBarHeight();
                if (staust == 0) {
                    staust = BaseTools.getStatusBarHeight(BaseApplication.getApp());
                    BasePersonSharePreference.saveStatusBarHeight(staust);
                }
                params.topMargin = staust;
            } else if (mView.getLayoutParams() instanceof RelativeLayout.LayoutParams) {
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mView.getLayoutParams();
                int staust = BasePersonSharePreference.getStatusBarHeight();
                if (staust == 0) {
                    staust = BaseTools.getStatusBarHeight(BaseApplication.getApp());
                    BasePersonSharePreference.saveStatusBarHeight(staust);
                }
                params.topMargin = staust;
            } else if (mView.getLayoutParams() instanceof FrameLayout.LayoutParams) {
                FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mView.getLayoutParams();
                int staust = BasePersonSharePreference.getStatusBarHeight();
                if (staust == 0) {
                    staust = BaseTools.getStatusBarHeight(BaseApplication.getApp());
                    BasePersonSharePreference.saveStatusBarHeight(staust);
                }
                params.topMargin = staust;
            }
        }

    }


    public static String mathLongTimeToFormat(Long time, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
//        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
//        sdf.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getDisplayName()));
        sdf.setTimeZone(TimeZone.getDefault());
        String sd = sdf.format(new Date(time));
        return sd;
    }



    /**
     * 把textView转换为图片
     */
    public static Bitmap textview2bitmap(View view) {
        view.setDrawingCacheEnabled(true);
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        Logger.i("info", "====textview2bitmap=" + view.getMeasuredWidth() + "===" + view.getMeasuredHeight());

        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        return view.getDrawingCache();
    }

    /**
     * 把textView转换为图片
     */
    public static Bitmap textview2bitmap(View view, int width) {
//		view.setDrawingCacheEnabled(true);
//		view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
//		Logger.i("info", "====textview2bitmap=" + view.getMeasuredWidth() + "===" + view.getMeasuredHeight());
//
//		view.layout(0, 0, width, width);
//		return view.getDrawingCache();
        if (null == view) {
            Logger.i("info", "=-======textview2bitmap= view=null====");
        }
        view.setLayoutParams(new ViewGroup.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        return bitmap;
    }

    //保留整
    public static String reserve2fPor(double res) {
        res = res * 100;
        String result = String.format("%.0f", res) + "%";
        return result;
    }

    /** 得到2个时间间的间距</n> time须大于当前时间  返回的数组[天,时,分,秒] */
    /**
     * @param time    结束时间
     * @param curtime 当前时间
     * @return String[] 数组 [天,时,分,秒]
     */
    public static String[] getCloseTime(long time, long curtime) {
        String[] close = new String[4];
        if (curtime > time) {
            close[0] = "00";
            close[1] = "00";
            close[2] = "00";
            close[3] = "00";
            return close;
        }

        try {
            SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date begin = dfs.parse(dfs.format(curtime));
            Date end = dfs.parse(dfs.format(new Date(time)));
            long between = (end.getTime() - begin.getTime()) / 1000;// 除以1000是为了转换成秒
            long day1 = between / (24 * 3600);
            long hour1 = between % (24 * 3600) / 3600;
            long minute1 = between % 3600 / 60;
            long second1 = between % 60 / 60;
            Logger.i("" + day1 + "天" + hour1 + "小时" + minute1 + "分" + second1 + "秒");

            close[0] = day1 > 9 ? day1 + "" : "0" + day1;
            close[1] = hour1 > 9 ? hour1 + "" : "0" + hour1;
            close[2] = minute1 > 9 ? minute1 + "" : "0" + minute1;
            close[3] = second1 > 9 ? second1 + "" : "0" + second1;
        } catch (Exception e) {
            close[0] = "00";
            close[1] = "00";
            close[2] = "00";
            close[3] = "00";
        }

        return close;
    }

    /**
     * 专门针对于赔率界面的时间计算方法
     */
    public static String getTimeForOdds(long time1, long time2) {
        try {
            String[] time = null;
            if (time1 > time2) {
                time = getCloseTime(time1 * 1000l, time2 * 1000l);
            } else {
                time = getCloseTime(time2 * 1000l, time1 * 1000l);
            }
            int h = Integer.parseInt(time[1]) + Integer.parseInt(time[0]) * 24;

            return "" + h + "h " + time[2] + "m";
        } catch (Exception e) {
            return "00h 00m";
        }
    }


    private static long lastClickTime;
    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        Logger.i("info", "=======time=" + time + "=timeD=" + timeD);
        if (0 < timeD && timeD < 500) {
            return false;
        }
        lastClickTime = time;
        return true;
    }


    /**
     * 6.0以上判断是否开启相机权限
     */
    public static boolean isCameraEnable() {
        boolean isCanUse = true;
        Camera mCamera = null;
        try {
            mCamera = Camera.open();
            Camera.Parameters mParameters = mCamera.getParameters(); //针对魅族手机
            mCamera.setParameters(mParameters);
        } catch (Exception e) {
            isCanUse = false;
        }

        if (mCamera != null) {
            try {
                mCamera.release();
            } catch (Exception e) {
                e.printStackTrace();
                return isCanUse;
            }
        }
        return isCanUse;
    }

    /**
     * 同步cookie
     * @param url
     * @param myCookie
     * @return
     */

//    public static boolean syncCookie(Context context, String url, String myCookie) {
//        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
//            CookieSyncManager.createInstance(context);
//        }
//        myCookie = myCookie.replace("[","");
//        myCookie = myCookie.replace("]","");
//        Logger.i("info","====myCookie="+myCookie);
//        CookieManager cookieManager = CookieManager.getInstance();
//        cookieManager.setAcceptCookie(true);
//        String cookies = cookieManager.getCookie(url);
//        Logger.i("info","===qian=cookies="+cookies);
//        cookieManager.removeAllCookie(); //remove
////        cookieManager.setCookie("http://caitest.laitouzhu.com", myCookie);//如果没有特殊需求，这里只需要将session id以"key=value"形式作为cookie即可
////        if(cookies!=null){
////            for (String cookie : cookies){
////                cookieManager.setCookie("http://caitest.laitouzhu.com",cookie);//注意端口号和域名，这种方式可以同步所有cookie，包括sessionid
////            }
////        }
//
//        cookieManager.setCookie(url, myCookie);//如果没有特殊需求，这里只需要将session id以"key=value"形式作为cookie即可
////        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
////        }else{
////            cookieManager.setCookie(url, myCookie);
////        }
//
//        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
//            CookieSyncManager.getInstance().sync();
////        }else{
////            cookieManager.flush();
//        }
//        String newCookie = cookieManager.getCookie(url);
//        Logger.i("info","====get=newCookie="+newCookie);
//        return TextUtils.isEmpty(newCookie)?false:true;
//    }


    public static boolean syncCookie(Context context, String url, List<Cookie> myCookie) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            CookieSyncManager.createInstance(context);
        }

        Logger.i("info","====myCookie="+myCookie.toString());
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        String cookies = cookieManager.getCookie(url);
        Logger.i("info","===qian=cookies="+cookies);
        cookieManager.removeAllCookie(); //remove
//        cookieManager.setCookie("http://caitest.laitouzhu.com", myCookie);//如果没有特殊需求，这里只需要将session id以"key=value"形式作为cookie即可
        if(cookies!=null){
            for (Cookie cookie : myCookie){
                Logger.i("info","===cookie.toString="+cookie.toString());
                cookieManager.setCookie(url,cookie.toString());//注意端口号和域名，这种方式可以同步所有cookie，包括sessionid
            }
        }

        //强制同步cookie 必须要做的。
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
            CookieSyncManager.getInstance().sync();
        }else{
            cookieManager.flush();
        }
        String newCookie = cookieManager.getCookie(url);
        Logger.i("info","====get=newCookie="+newCookie);
        return TextUtils.isEmpty(newCookie)?false:true;
    }

    /**
     * 清除WebView缓存
     */
    public static void clearWebViewCache(Context context,String path){

        //清理Webview缓存数据库
        try {
            context.deleteDatabase("webview.db");
            context.deleteDatabase("webviewCache.db");

            //WebView 缓存文件
//            File appCacheDir = new File(context.getFilesDir().getAbsolutePath()+path);
            Logger.i("clearWebViewCache","===path="+path);
            File appCacheDir = new File(path);
            Log.e("clearWebViewCache", "appCacheDir path="+appCacheDir.getAbsolutePath());

            File webviewCacheDir = new File(context.getCacheDir().getAbsolutePath()+"/webviewCache");
            Log.e("clearWebViewCache", "webviewCacheDir path="+webviewCacheDir.getAbsolutePath());

            //删除webview 缓存目录
            if(webviewCacheDir.exists()){
                deleteFile(webviewCacheDir);
            }
            //删除webview 缓存 缓存目录
            if(appCacheDir.exists()){
                deleteFile(appCacheDir);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 递归删除 文件/文件夹
     *
     * @param file
     */
    public static void deleteFile(File file) {

        Log.i("deleteFile", "delete file path=" + file.getAbsolutePath());

        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
        } else {
            Log.e("deleteFile", "delete file no exists " + file.getAbsolutePath());
        }
    }

    /**
     * 到对应的 action_view
     * @param activity
     * @param url
     * @param dataType
     */
    public static void actionViewActivity(Activity activity,String url,String dataType){
        try {
            Uri uri = Uri.parse(url);
            //调用系统自带的播放器
            Intent intent = new Intent(Intent.ACTION_VIEW);

            if(StrUtil.isNotEmpty(dataType)){
                intent.setDataAndType(uri,dataType);
            }else{
                intent.setData(uri);
            }
            activity.startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
